package yanc.app

import grails.converters.JSON
import org.slf4j.Logger
import org.slf4j.LoggerFactory

class PhoneController {
    def phoneService
    static final Logger logger = LoggerFactory.getLogger(PhoneController.class)

    def add() {
        def data = [:]
        def imgUrl = "${params.imgUrl ?: ''}"
        def phoneComm = "${params.phoneComm ?: ''}"
        try {
            def phone1 = Phone.findByPhoneComm(phoneComm)
            if (phone1) {
                data << [statuCode: "1", errMsg: "1"]

            } else {
                phoneService.add(phoneComm, imgUrl)
                def list = Phone.list()
                data << [statuCode: "0", errMsg: "0", data: list]
            }
            render data as JSON
        } catch (Exception e) {
            logger.error("PhoneController add Exception" + e.message)
        }
    }

    def getAll() {
        def data = [:]
        def list = Phone.list()
        if (list) {
            data << [statuCode: "0", errMsg: "0", data: list]
        } else {
            data << [statuCode: "1", errMsg: "1"]
        }
        render data as JSON
    }

    def getAlls() {
        def data = [:]
        def list = Phone.list()
        def lists = []
        for (int i = 0; i < list.size(); i++) {
            def map = [:]
            map.put("label", list[i].phoneComm)
            map.put("value", list[i].id + "")
            lists.add(map)
        }
        if (list) {
            data << [statuCode: "0", errMsg: "0", data: lists]
        } else {
            data << [statuCode: "1", errMsg: "1"]
        }
        render data as JSON
    }


    def refresh() {
        def data = [:]
        def id = Integer.parseInt("${params.id}")
        def imgUrl = "${params.imgUrl ?: ''}"
        try {
            def phone = Phone.findById(id)
            bindData(phone, params, [exclude: ['id', 'imgUrl']])
            phoneService.update(phone, imgUrl)
            def list = Phone.list()
            data << [statuCode: "0", errMsg: "0", data: list]
            render data as JSON
        } catch (Exception e) {
            logger.error("PhoneController refresh Exception" + e.message)
        }
    }

    def del() {
        def data = [:]
        def id = Integer.parseInt("${params.id}")
        try {
            phoneService.del(id)
            def list = Phone.list()
            data << [statuCode: "0", errMsg: "0", data: list]
            render data as JSON
        } catch (Exception e) {
            logger.error("PhoneController del Exception" + e.message)
        }
    }
}
